<template>
    <el-dialog
        v-model="dialogVisible"
        :title="title"
        width="500"
        :before-close="handleClose"
    >
        <el-form
          ref="formEl"
          style="max-width: 600px"
          :model="dataForm"
          :rules="rules"
          label-width="auto"
        >
            <el-form-item label="字典标签" prop="label">
              <el-input v-model="dataForm.label" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="值类型" prop="valueType">
              <el-select v-model="dataForm.valueType" placeholder="请选择" @change="handleChangeType">
                <el-option v-for="item in valueTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="字典值" prop="value">
              <el-input v-if="dataForm.valueType === 'string'" v-model="dataForm.value" placeholder="请输入" />
              <el-input-number v-if="dataForm.valueType ==='number'" v-model="dataForm.value" controls-position="right" />
              <el-checkbox v-if="dataForm.valueType ==='boolean'" v-model="dataForm.value" />
              <el-input v-if="dataForm.valueType ==='array'" v-model="dataForm.value" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="颜色" prop="color">
              <el-color-picker v-model="dataForm.color" />
            </el-form-item>
            
            <el-form-item label="状态" prop="status">
              <el-select v-model="dataForm.status" placeholder="请选择" >
                <el-option label="启用" value="open" />
                <el-option label="禁用" value="close" />
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" placeholder="请输入" />
            </el-form-item>

        </el-form>
        <template #footer>
        <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
        </div>
        </template>
    </el-dialog>
</template>

<script setup>
  import DictAPI from '@/api/system/dict.api'
  import useToggle from "@/hooks/useToggle";
  const [dialogVisible, , setDialogVisible] = useToggle();


  const valueTypes = ref([
    { label: '字符串', value: 'string' },
    { label: '数字', value: 'number' },
    { label: '布尔', value: 'boolean' },
    { label: '数组', value: 'array' },
  ])

  const emit = defineEmits(['refresh'])

  const title = ref('新增字典')
  
  const dataForm = ref({
    typeId: void undefined,
    valueType: 'string',
    value: void undefined,
    label: void undefined,
    color: '#409EFF',
    status: void undefined,
    remark: void undefined,
  })

  const rules = reactive({
    value: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (dataForm.value.valueType === 'boolean') {
            if (value === undefined || value === null) {
              callback(new Error('请选择字典值'));
            } else {
              callback();
            }
          } else if (dataForm.value.valueType === 'string' || dataForm.value.valueType === 'array') {
            if (!value) {
              callback(new Error('请输入字典值'));
            } else {
              callback();
            }
          } else if (dataForm.value.valueType === 'number') {
            if (value === undefined || value === null) {
              callback(new Error('请输入字典值'));
            } else if (isNaN(value)) {
              callback(new Error('请输入有效的数字'));
            } else {
              callback();
            }
          } else {
            callback(); // 其他类型不校验
          }
        },
        trigger: ['blur', 'change'],
      },
    ],
    valueType: [
      { required: true, message: '请选择值类型', trigger: 'change' },
    ],
    label: [
      { required: true, message: '请输入字典标签', trigger: 'blur' },
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' },
    ],
    color: [
      { required: true, message: '请选择颜色', trigger: 'change' },
    ]
  })

  const handleChangeType = (value) => {
    if(value === 'boolean') {
      dataForm.value.value = false;
    } else {
      dataForm.value.value = void undefined;
    }
  }

  const formEl = ref(null)
  const submit = async () => {
    await formEl.value.validate((valid, fields) => {
      if (valid) {
        const params = JSON.parse(JSON.stringify(dataForm.value));
        if(dataForm.value.valueType === 'array') {
          params.value = JSON.parse(dataForm.value.value);
        }
        DictAPI.addData(params).then(res => {
          ElMessage.success('新增成功')
          emit('refresh')
          setDialogVisible(false)
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const handleClose = () => {
    setDialogVisible(false);
  }

  const handleOpen = (typeId, row) => {
    if(!typeId) return ElMessage.error('请选择字典类型')

    if(row) {
      dataForm.value = JSON.parse(JSON.stringify(row));
      dataForm.value.valueType = typeof dataForm.value.value;
      if(dataForm.value.valueType === 'object') {
        dataForm.value.valueType = Array.isArray(dataForm.value.value) ? 'array' : 'object';
        dataForm.value.value = JSON.stringify(dataForm.value.value)
      }
      title.value = '编辑字典'
    } else {
      dataForm.value = {
        typeId: void undefined,
        valueType: 'string',
        value: void undefined,
        label: void undefined,
        color: '#409EFF',
        status: void undefined,
        remark: void undefined,
      }
      title.value = '新增字典'
    }

    dataForm.value.typeId = typeId;

    setDialogVisible(true);
  }

  defineExpose({
    handleOpen
  })
</script>
